package com.example.bootcurriculumproject.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;
//    @Autowired
//    public RedisUtil(RedisTemplate<String, Serializable> redisTemplate) {
//        this.redisTemplate = redisTemplate;
//    }
    //删除缓存
    public void delRedis(String... key){
        if(key!=null && key.length>0){
            if(key.length == 1){
                redisTemplate.delete(key[0]);
            }else {
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }
    //添加缓存
    public boolean set(String key, Serializable value, long timeout) throws
            RuntimeException{
        long min = 1;
        long max = timeout / 5;
        if (timeout > 0) {
            //增加随机数，防⽌雪崩
            timeout += (long) new Random().nextDouble() * (max - min);
            redisTemplate.opsForValue().set(key, value, timeout,
                    TimeUnit.SECONDS);
        }else{
            redisTemplate.opsForValue().set(key, value);
        }
        return true;
    }
    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public Serializable get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
    /**
     * 判断redis中是否存在键值
     * @param key 键
     * @return
     */
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }
}
